﻿using System;
using System.Reflection;

namespace SMARTMobile.WinPhone
{
    public static class CopyUtility
    {
        public static T CopyFrom<T, Y>(this T targetEntity, Y sourceEntity)
        {
            if (targetEntity == null || sourceEntity == null)
            {
                return targetEntity;
            }

            foreach (PropertyInfo targetPI in targetEntity.GetType().GetProperties())
            {
                PropertyInfo sourcePropertyInfo = sourceEntity.GetType().GetProperty(targetPI.Name);
                if (sourcePropertyInfo != null && targetPI.CanWrite && sourcePropertyInfo.CanRead && targetPI.Name != "EntityKey")
                {
                    try
                    {
                        targetPI.SetValue(targetEntity, sourcePropertyInfo.GetValue(sourceEntity, null), null);
                    }
                    catch
                    {
                        //// Skip this property
                    }
                }
            }

            return targetEntity;
        }

        public static void CopyTo(this object source, object target)
        {
            if (target == null || source == null)
            {
                return;
            }

            foreach (var pS in source.GetType().GetProperties())
            {
                foreach (var pT in target.GetType().GetProperties())
                {
                    if (pT.Name != pS.Name)
                    {
                        continue;
                    }

                    if (pT.GetSetMethod() == null)
                    {
                        continue;
                    }

                    try
                    {
                        pT.GetSetMethod().Invoke(target, new object[] { pS.GetGetMethod().Invoke(source, null) });
                    }
                    catch (Exception ex)
                    {
                        // can't copy properties when set null
                    }
                }
            };
        }
    }
}